﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Golem.Indexer.Search
{
    internal static class Helper
    {
        public static String GetNetworkIp(this String ip, String mask)
        {
            var ipBlock = ip.Split('.');
            var maskBlock = mask.Split('.');

            for (int i = 0; i < ipBlock.Length; i++)
            {
                var ipCell = Convert.ToInt32(ipBlock[i]);
                var backupIPCell = ipCell;
                var maskCell = Convert.ToInt32(maskBlock[i]);

                ipCell &= maskCell;
                ipCell |= backupIPCell;
                ipBlock[i] = ipCell.ToString();
            }

            return String.Format("{0}.{1}.{2}.{3}", ipBlock[0], ipBlock[1], ipBlock[2], ipBlock[3]);
        }

        public static String ToIP(this String[] ipBlock)
        {
            return String.Format("{0}.{1}.{2}.{3}", ipBlock[0], ipBlock[1], ipBlock[2], ipBlock[3]);
        }

        public static int GetHostCountByMask(this String mask)
        {
            var maskBlock = mask.Split('.');

            int allHostsCount = 1;
            for (int i = 0; i < maskBlock.Length; i++)
            {
                var maskCell = Convert.ToInt32(maskBlock[i]);
                var hostsCount = 256 - maskCell;
                allHostsCount *= hostsCount;
            }

            return allHostsCount;
        }

        public static int SparseBitcount(this int n)
        {
            int count = 0;
            while (n != 0)
            {
                count++;
                n &= (n - 1);
            }
            return count;
        }

    }
}
